package com.dsr.util;


import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author dsr
 * @since 2021-03-13 22:16
 */
@Component
public class FileUtil {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    public String  uploadFiles(MultipartFile file) throws Exception {
        OSSClient ossClient = new OSSClient(bucketName,accessKeyId,accessKeySecret);
        String key =renameToUUID(file.getOriginalFilename());
        ossClient.setEndpoint(endpoint);
        ossClient.putObject(bucketName,key, file.getInputStream());

        return "http://"+bucketName+"."+endpoint+"/"+key;
    }
    private   String renameToUUID(String fileName) {
        return UUID.randomUUID()  + fileName.substring(fileName.lastIndexOf(".") );
    }

}
